from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import render


# Create your views here.
from django.template.context_processors import request
from django.views import View


def login_view(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        # 与数据库中的用户名和密码比对，django默认保存密码是以哈希形式存储，并不是明文密码，这里的password验证默认调用的是User类的check_password方法，以哈希值比较。
        user = authenticate(request, username=username, password=password)
        # 验证如果用户不为空
        if user is not None:
            # login方法登录
            login(request, user)
            # 返回登录成功信息
            return HttpResponse('登陆成功')
        else:
            # 返回登录失败信息
            return HttpResponse('登陆失败')

    return render(request, 'users/login.html')


def user_status(request):
    return HttpResponse(f'当前登录用户: {request.user.username}')


class Logout(View):
    def get(self, request, *args, **kwargs):
        logout(request)
        username = request.user.username
        if not username:
            return HttpResponse('注销成功')
        else:
            return HttpResponse('注销失败')

    def post(self, request, *args, **kwargs):
        self.get(request, args, kwargs)


@permission_required(perm="apps.customize_permission", raise_exception=False, login_url="login")
def setting_status(request):

    # 判断权限
    user = request.user
    print(user.get_user_permissions())
    # has_permission = user.has_perm('apps.customize_permission')
    # print(has_permission)

    f = open("test_django/settings.py", "r", encoding="utf-8")
    return HttpResponse(f.read())

